package com.nf1000.balancelibrary.newbalance;

import android.annotation.SuppressLint;

/**
 * 解析工具
 * @author leon
 *
 */
@SuppressLint("DefaultLocale")
public class ParseUtil {
	private static java.text.DecimalFormat dfc = new java.text.DecimalFormat("#.#");
	
	public static String[] parse(String content) {
		byte[] data = hexStringToBytes(content);

		// 设别类型
		int v = data[0] & 0xFF;

		// 体重
		int weight = (data[4] << 8) | (data[5] & 0xff);
		float scale = (float) 0.1;
		if (v == 0xcf) {
			scale = (float) 0.1;
		} else if (v == 0xce) {
			scale = (float) 0.1;
		} else if (v == 0xcb) {
			scale = (float) 0.01;
		} else if (v == 0xca) {
			scale = (float) 0.001;
		}

		float weightRec = scale * weight;

		if (weightRec < 0) {
			weightRec *= -1;
		}

		// 脂肪
		int zhifang = (data[6] << 8) | (data[7] & 0xff);

		float zhifangRate = (float) (zhifang * 0.1);
		// 骨骼
		int guge = data[8] & 0xff;

		float gugeRate = (float) ((guge * 0.1) / weightRec) * 100;

		// 肌肉含量
		int jirou = (data[9] << 8) | (data[10] & 0xff);
		float jirouRate = (float) (jirou * 0.1);

		// 内脏脂肪等级
		int neizang = data[11] & 0xff;
		int neizanglevel = neizang * 1;

		// 水份含量
		int water = data[12] << 8 | data[13];
		float waterRate = (float) (water * 0.1);

		// 热量含量
		int hot = data[14] << 8 | (data[15] & 0xff);

		String[] rec = new String[]{"体重:" + dfc.format(weightRec < 0 ? -weightRec : weightRec) + "Kg", "骨骼:" + dfc.format(gugeRate < 0 ? -gugeRate : gugeRate) + "%", "脂肪:" + dfc.format(zhifangRate < 0 ? -zhifangRate : zhifangRate) + "%",
				"肌肉:" + dfc.format(jirouRate < 0 ? -jirouRate : jirouRate) + "%", "水分:" + dfc.format(waterRate < 0 ? -waterRate : waterRate) + "%", "内脏脂肪:" + dfc.format(neizanglevel < 0 ? -neizanglevel : neizanglevel), "BMR:" + dfc.format(hot < 0 ? -hot : hot) + "kcal"};

		return rec;
	}
	
	@SuppressLint("DefaultLocale")
	public static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}
	
	public static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}
	
	/**获取结果数据*/
	public static String getResult(byte[] value){
		StringBuilder stringBuilder = new StringBuilder("");
		for (int i = 0; i < value.length; i++) {
			int v = value[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		
		return stringBuilder.toString();
	}

}
